﻿using System;
using System.Data;
using System.Data.SqlClient;

namespace WebApplication1
{
    class SqlHelper
    {
        public string constr = "server=.;uid=sa;pass=123456;database=Student_db";
        public SqlConnection con = null;
        public SqlHelper() 
        {
            con = new SqlConnection(constr);
        }
        public DataTable Get(string sql, SqlParameter[] pars)
        {
            try
            {
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }
                SqlCommand com = new SqlCommand(sql, con);
                if (pars != null)
                {
                    com.Parameters.AddRange(pars);
                }
                SqlDataAdapter sdq = new SqlDataAdapter(com);
                DataSet dataSet = new DataSet();
                sdq.Fill(dataSet);
            }
            catch (Exception x)
            {

                throw new Exception(x.Message);
            }
            finally 
            {
                if (con!=null)
                {
                    con.Close();
                }
            }
        }

        public bool Execute(string sql, SqlParameter[] pars)
        {
            try
            {
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }
                SqlCommand cmd = new SqlCommand(sql, con);
                if (pars != null)
                {
                    cmd.Parameters.AddRange(pars);
                }
                return cmd.ExecuteNonQuery() > 0 ? true :  false;
            }
            catch (Exception c)
            {
                throw new Exception(c.Message);
            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }
    }
}